package com.ky.h5house;

import android.Manifest;
import android.app.Dialog;
import android.content.Context;

import android.os.Build;
import android.os.Bundle;

import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebStorage;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.amap.api.location.AMapLocation;
import com.google.gson.Gson;
import com.ky.h5house.base.Constants;
import com.ky.h5house.bean.LocationBean;
import com.ky.h5house.databinding.ActivityMainBinding;
import com.ky.h5house.utils.AMapLocationUtil;
import com.ky.h5house.utils.DialogUtils;
import com.tbruyelle.rxpermissions.RxPermissions;

import java.util.ArrayList;
import java.util.List;


public class MainActivity extends AppCompatActivity {
    ActivityMainBinding mBinding;
    /**
     * js接口
     */
    private WebAppInterface webAppInterface = new WebAppInterface(this);

    private String home = Constants.HOME;
    /**
     * 定位信息
     */
    AMapLocation aMapLocation;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setSystemUiVisible(false);
        mBinding = ActivityMainBinding.inflate(LayoutInflater.from(this));
        setContentView(mBinding.getRoot());


        configWeb();
        requestPermission(this, new PermissionCall() {
            @Override
            public void granted() {
//                location();
                mBinding.webView.loadUrl(home);
            }

            @Override
            public void denied() {
                setLoadingStyle(View.VISIBLE, "加载中...");
                mBinding.webView.loadUrl(home);
//                Toast.makeText(MainActivity.this, "请先允许定位权限", Toast.LENGTH_SHORT).show();
            }
        }, getNeedPermissions());
    }


    private int locationErrorCount = 0;

    private void location() {
        AMapLocationUtil.getCurrentLocation(location -> {
            if (location != null) {
                double latitude = location.getLatitude();
                double longitude = location.getLongitude();
                if (latitude > 0 && longitude > 0) {
                    setLoadingStyle(View.VISIBLE, "加载中");
                    aMapLocation = location;
                    mBinding.webView.loadUrl(home);
                } else {
                    locationErrorCount++;
                    if (locationErrorCount <= 15) {
                        //递归
                        location();
                    } else {
                        setLoadingStyle(View.VISIBLE, "加载中");
                        mBinding.webView.loadUrl(home);
                    }
                }
            }
        });
    }

    /**
     * 配置网页
     */
    private void configWeb() {
        //清除缓存
//        mBinding.webView.clearCache(true);
        WebSettings webSettings = mBinding.webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);
        //支持放大
        webSettings.setSupportZoom(true);
        //开启定位
        webSettings.setGeolocationEnabled(true);
        // 启动应用缓存
        webSettings.setAppCacheEnabled(false);
        // 设置缓存模式
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        //setAppCacheEnabled与setCacheMode对localStorage无效，要删除需要使用deleteAllData方法
        //WebStorage.getInstance().deleteAllData();
        //自适应屏幕
        webSettings.setUseWideViewPort(true);
        //支持通过JS打开新窗口
        webSettings.setMediaPlaybackRequiresUserGesture(false);//设置音频自动播放
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        // webView从5.0开始默认不允许混合模式,https中不能加载http资源,需要设置开启。
        webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        mBinding.webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                if (mBinding.progressBar.isShown()) {
                    if (newProgress > 85) {
                        setLoadingStyle(View.GONE, "加载完成");
                    }
                }
            }
        });
        mBinding.webView.addJavascriptInterface(webAppInterface, "Android");
        mBinding.webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                if (mBinding.progressBar.isShown()) {
                    setLoadingStyle(View.GONE, "加载完成");
                }
            }
        });
        mBinding.btn1.setOnClickListener(v -> {
            stopTimeCount();
            startTimeCount();
            btn2ClickCount = 0;
            btn3ClickCount = 0;
            btn1ClickCount++;
        });
        mBinding.btn2.setOnClickListener(v -> {
            stopTimeCount();
            startTimeCount();
            btn3ClickCount = 0;
            btn2ClickCount++;
        });
        mBinding.btn3.setOnClickListener(v -> {
            stopTimeCount();
            startTimeCount();
            btn3ClickCount++;
            if (btn1ClickCount == 3 && btn2ClickCount == 1 && btn3ClickCount == 2) {
                DialogUtils.showCommonDialog(this, "你确定要退出应用吗？", "取消", "确定", new DialogUtils.IDialogItemListener() {
                    @Override
                    public void positive(Dialog dialog) {
                        finish();
                    }

                    @Override
                    public void negative(Dialog dialog) {
                        btn1ClickCount = 0;
                        btn2ClickCount = 0;
                        btn3ClickCount = 0;
                        stopTimeCount();
                    }
                });
            }
        });
    }

    int btn1ClickCount = 0;//按钮1点击次数3
    int btn2ClickCount = 0;//按钮2点击次数3
    int btn3ClickCount = 0;//按钮3点击次数3

    @Override
    protected void onResume() {
        super.onResume();
        setSystemUiVisible(false);
    }


    /**
     * 获取权限
     *
     * @return 权限数组
     */
    private String[] getNeedPermissions() {
        List<String> permissions = new ArrayList<>();
//        permissions.add(Manifest.permission.ACCESS_FINE_LOCATION);
//        permissions.add(Manifest.permission.ACCESS_COARSE_LOCATION);
        permissions.add(Manifest.permission.ACCESS_NETWORK_STATE);
//        permissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
//        permissions.add(Manifest.permission.READ_EXTERNAL_STORAGE);
//        permissions.add(Manifest.permission.READ_PHONE_STATE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && getApplicationContext().getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.Q) {
//            permissions.add(Manifest.permission.ACCESS_BACKGROUND_LOCATION);
            permissions.add(Manifest.permission.SYSTEM_ALERT_WINDOW);
        }
        return permissions.toArray(new String[0]);

    }

    /**
     * 权限请求方法
     *
     * @param context     上下文
     * @param call        回调
     * @param permissions 需要申请的权限名称
     */
    public static void requestPermission(Context context, final PermissionCall call,
                                         final String... permissions) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // 大于等于23，去申请权限
            RxPermissions.getInstance(context.getApplicationContext())
                    //多个权限用","隔开
                    .request(permissions)
                    .subscribe(aBoolean -> {
                        if (aBoolean) {
                            call.granted();
                        } else {
                            call.denied();
                        }
                    });
        } else {
            call.granted();
        }
    }


    /**
     * 权限回调接口方法
     */
    public interface PermissionCall {
        //授予
        void granted();

        //拒绝
        void denied();
    }

    /**
     * 注入到JS
     */
    class WebAppInterface {
        Context mContext;

        public WebAppInterface(Context c) {
            mContext = c;
        }

        /**
         * 向网页传递定位信息
         *
         * @return 经纬度json字符串
         */
        @JavascriptInterface
        public String postLocation() {
            LocationBean bean = new LocationBean();
            if (aMapLocation != null) {
                double latitude = aMapLocation.getLatitude();
                double longitude = aMapLocation.getLongitude();
                bean.setLatitude(String.valueOf(latitude));
                bean.setLongitude(String.valueOf(longitude));
            }
            String json = new Gson().toJson(bean);
//            Log.d("postLocation", json);
            return json;
        }
    }

    /**
     * 加载样式，显示隐藏
     *
     * @param visible 是否显示隐藏
     * @param text    加载提示文本
     */
    private void setLoadingStyle(int visible, String text) {
        runOnUiThread(() -> {
            mBinding.progressBar.setVisibility(visible);
            mBinding.tvStatus.setVisibility(visible);
            mBinding.tvStatus.setText(text);
        });
    }

    /**
     * 是否显示状态栏和导航栏
     *
     * @param visible 是否展示
     */
    private void setSystemUiVisible(boolean visible) {
        int uiFlag;
        if (visible) {
            uiFlag = View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
        } else {
            uiFlag = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;

        }
        uiFlag |= View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
        getWindow().getDecorView().setSystemUiVisibility(uiFlag);
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            //监控/拦截/屏蔽返回键
            return false;
        } else if (keyCode == KeyEvent.KEYCODE_MENU) {
            return false;
        } else if (keyCode == KeyEvent.KEYCODE_HOME) {
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    int countTimeCount = 10;

    Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                if (countTimeCount > 0) {
                    countTimeCount--;
                    startTimeCount();
                } else {
                    countTimeCount = 10;
                    btn1ClickCount = 0;
                    btn2ClickCount = 0;
                    btn3ClickCount = 0;
                    stopTimeCount();
                }
            }
        }
    };

    void startTimeCount() {
        mHandler.sendEmptyMessageDelayed(1, 1000);
    }

    void stopTimeCount() {
        mHandler.removeCallbacksAndMessages(null);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopTimeCount();
    }
}